package com.nepu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nepu.gmall.realtime.app.func.DimAsyncFunction;
import com.nepu.gmall.realtime.bean.TradeTrademarkCategoryUserRefundBean;
import com.nepu.gmall.realtime.util.ClickHouseUtil;
import com.nepu.gmall.realtime.util.DateFormatUtil;
import com.nepu.gmall.realtime.util.KafkaUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * 交易域品牌-品类-用户粒度退单各窗口汇总表
 * 	从 Kafka 读取退单明细数据，过滤 null 数据并按照唯一键对数据去重，
 * 	关联维度信息，按照维度分组，统计各维度各窗口的订单数和订单金额，
 * 	将数据写入 ClickHouse 交易域品牌-品类-用户粒度退单各窗口汇总表。
 *
 * 	（1）从kafka的dwd_trade_order_refund的主题中消费数据
 * 	（2）将数据转换成javabean
 * 	（3）关联维表
 * 	（4）提取时间时间生成watermark
 * 	 (5) 将数据按照key进行分组
 * 	（6）开窗聚合
 * 	（7）补全维度信息
 * 	（8）将数据写入到clickHouse
 * 	
 * 	数据流向：
 * 	mock --> mysql --> maxwell --> kafka --> DwdTradeOrderRefund.class --> kafka --> DwsTradeTrademarkCategoryUserRefundWindow.class --> clickHouse
 * 	
 * 	需要启动的服务：
 * 	mysql maxwell redis clickhouse zookeeper kafka hbase hdfs phoenix 
 * @author chenshuaijun
 * @create 2023-03-06 17:06
 */
public class DwsTradeTrademarkCategoryUserRefundWindow {

    public static void main(String[] args) throws Exception {
        // TODO 1、加载流式的处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 生产环境下是一定不会将任务的并行度设置为1的，这里具体的设置是和我们等下要读取的kafka的相应的主题的分区的个数相同
        env.setParallelism(1);
        // 设置checkpoint的信息：设置checkpoint的间隔是5分钟,并且checkpoint的级别是精确一次性
        /*env.enableCheckpointing(5 * 60000L, CheckpointingMode.EXACTLY_ONCE);
        // 设置checkpoint的超时时间是10分钟
        env.getCheckpointConfig().setCheckpointTimeout(10 * 60000L);
        // 设置外部检查点。可以将检查点的元数据信息定期写入外部系统，这样当job失败时，检查点不会被清除。这样如果job失败，可以从检查点恢复job。
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        // 设置checkpoint的重启的策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)));
        // 设置两个checkpoint之间的最小的间隔时间
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
        // 设置状态后端: 设置状态后端为内存级别
        env.setStateBackend(new HashMapStateBackend());
        // 设置checkpoint的存储的路径
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/checkpoint");
        // 因为我们的HDFS只有atguigu用户才能够操作，所以要将用户设置为atguigu
        System.setProperty("HADOOP_USER_NAME", "atguigu");*/
        // TODO 2、从kafka的dwd_trade_order_detail主题中消费数据
        String topic = "dwd_trade_order_refund";
        DataStreamSource<String> dwsTradeRefundOrderDS= env.addSource(KafkaUtils.getKafkaConsumer(topic, "DwsTradeTrademarkCategoryUserRefundWindow"));
        
        // TODO 3、转换数据结构到javaBean
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> refundDS = dwsTradeRefundOrderDS.map(new MapFunction<String, TradeTrademarkCategoryUserRefundBean>() {
            @Override
            public TradeTrademarkCategoryUserRefundBean map(String value) throws Exception {
                JSONObject jsonObject = JSON.parseObject(value);
                HashSet<String> set = new HashSet<>();
                set.add(jsonObject.getString("order_id"));
                return TradeTrademarkCategoryUserRefundBean.builder()
                        .skuId(jsonObject.getString("sku_id"))
                        .userId(jsonObject.getString("user_id"))
                        .orderIdSet(set)
                        .ts(DateFormatUtil.toTs(jsonObject.getString("create_time"), true))
                        .build();
            }
        });
        // TODO 4、关联维表
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> tradeTrademarkCategoryUserRefundDs = AsyncDataStream.unorderedWait(refundDS, new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>("DIM_SKU_INFO") {
            @Override
            public String getKey(TradeTrademarkCategoryUserRefundBean input) {
                return input.getSkuId();
            }

            @Override
            public void encapsulateBeans(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setTrademarkId(dimInfo.getString("TM_ID"));
                input.setCategory3Id(dimInfo.getString("CATEGORY3_ID"));
            }
        }, 100, TimeUnit.SECONDS);

        // TODO 5、提取事件时间生成watermark
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> watermarkDS = tradeTrademarkCategoryUserRefundDs.assignTimestampsAndWatermarks(WatermarkStrategy.<TradeTrademarkCategoryUserRefundBean>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<TradeTrademarkCategoryUserRefundBean>() {
            @Override
            public long extractTimestamp(TradeTrademarkCategoryUserRefundBean element, long recordTimestamp) {
                return element.getTs();
            }
        }));
        // TODO 6、分组开窗聚合
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> reduceDS = watermarkDS.keyBy(new KeySelector<TradeTrademarkCategoryUserRefundBean, Tuple3<String, String, String>>() {
            @Override
            public Tuple3<String, String, String> getKey(TradeTrademarkCategoryUserRefundBean value) throws Exception {
                return Tuple3.of(value.getUserId(), value.getTrademarkId(), value.getCategory3Id());
            }
        }).window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean reduce(TradeTrademarkCategoryUserRefundBean value1, TradeTrademarkCategoryUserRefundBean value2) throws Exception {
                        value1.getOrderIdSet().addAll(value2.getOrderIdSet());
                        return value1;
                    }
                }, new WindowFunction<TradeTrademarkCategoryUserRefundBean, TradeTrademarkCategoryUserRefundBean, Tuple3<String, String, String>, TimeWindow>() {
                    @Override
                    public void apply(Tuple3<String, String, String> stringStringStringTuple3, TimeWindow window, Iterable<TradeTrademarkCategoryUserRefundBean> input, Collector<TradeTrademarkCategoryUserRefundBean> out) throws Exception {
                        TradeTrademarkCategoryUserRefundBean tradeTrademarkCategoryUserRefundBean = input.iterator().next();
                        tradeTrademarkCategoryUserRefundBean.setRefundCount((long) tradeTrademarkCategoryUserRefundBean.getOrderIdSet().size());
                        tradeTrademarkCategoryUserRefundBean.setTs(System.currentTimeMillis());
                        tradeTrademarkCategoryUserRefundBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        tradeTrademarkCategoryUserRefundBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        out.collect(tradeTrademarkCategoryUserRefundBean);
                    }
                });

        // TODO 7 补全tm字段
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> tmDS = AsyncDataStream.unorderedWait(reduceDS, new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>("DIM_BASE_TRADEMARK") {
            @Override
            public String getKey(TradeTrademarkCategoryUserRefundBean input) {
                return input.getTrademarkId();
            }

            @Override
            public void encapsulateBeans(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setTrademarkName(dimInfo.getString("TM_NAME"));
            }
        }, 100, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> ctThreeDS = AsyncDataStream.unorderedWait(tmDS, new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>("DIM_BASE_CATEGORY3") {
            @Override
            public String getKey(TradeTrademarkCategoryUserRefundBean input) {
                return input.getCategory3Id();
            }

            @Override
            public void encapsulateBeans(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setCategory3Name(dimInfo.getString("NAME"));
                input.setCategory2Id(dimInfo.getString("CATEGORY2_ID"));
            }
        }, 100, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> ctTowDS = AsyncDataStream.unorderedWait(ctThreeDS, new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>("DIM_BASE_CATEGORY2") {
            @Override
            public String getKey(TradeTrademarkCategoryUserRefundBean input) {
                return input.getCategory2Id();
            }

            @Override
            public void encapsulateBeans(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setCategory2Name(dimInfo.getString("NAME"));
                input.setCategory1Id(dimInfo.getString("CATEGORY1_ID"));
            }
        }, 100, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> resultDS = AsyncDataStream.unorderedWait(ctTowDS, new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>("DIM_BASE_CATEGORY1") {
            @Override
            public String getKey(TradeTrademarkCategoryUserRefundBean input) {
                return input.getCategory1Id();
            }

            @Override
            public void encapsulateBeans(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setCategory1Name(dimInfo.getString("NAME"));
            }
        }, 100, TimeUnit.SECONDS);

        resultDS.print(">>>>>>>>>>>>>>>>>");
        resultDS.addSink(ClickHouseUtil.getJdbcSink("insert into dws_trade_trademark_category_user_refund_window values(?,?,?,?,?,?,?,?,?,?,?,?,?)"));

        env.execute("DwsTradeTrademarkCategoryUserRefundWindow");

    }
}
